package com.wallace.downloadserver.netty.handler.outbound

import com.wallace.downloadserver.netty.NettyManager
import com.wallace.downloadserver.netty.handler.inbound.NettyMsgDecryptHandler
import com.wallace.downloadserver.util.myEncrypt.AESCryptUtil
import com.wallace.downloadserver.util.myEncrypt.AESKey
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelOutboundHandlerAdapter
import io.netty.channel.ChannelPromise
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.net.InetSocketAddress
import java.net.SocketAddress

/**
 * @Description:
 * Netty消息加密处理
 * @author Wallace
 * @Date 2022/2/14 16:44
 */
@Component
class NettyMsgEncryptHandler(private var nettyManager: NettyManager) : ChannelOutboundHandlerAdapter() {

    private val log: Logger = LoggerFactory.getLogger(NettyMsgDecryptHandler::class.java)

    private var aesKey: AESKey? = null

    override fun connect(ctx: ChannelHandlerContext?, remoteAddress: SocketAddress?, localAddress: SocketAddress?, promise: ChannelPromise?) {
        val ip = (remoteAddress as? InetSocketAddress)?.address?.hostAddress
        ip?.let {
            aesKey = nettyManager.initAesKey(ip)
            log.debug("connect to client[${ip}] ")
        }
    }

    override fun write(ctx: ChannelHandlerContext?, msg: Any, promise: ChannelPromise?) {
        val jsonString = (msg as? ByteBuf)?.toString(Charsets.UTF_8)
        if (jsonString != null) {
            val cipher = AESCryptUtil.encryptAndEncode(jsonString.toByteArray(), aesKey!!.getSecretKeySpec(), aesKey!!.iv)
            if (cipher != null) {
                log.info("send message to client[${ctx?.channel()?.remoteAddress()}] : ${cipher.toString(Charsets.UTF_8)}")
                ctx?.writeAndFlush(cipher)
            }
        } else {
            log.debug("msg.javaClass = ${msg.javaClass}")
        }
    }
}